﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BankSystem.Classes
{
    public delegate void BigMoneyFetched(bool storeOrwithdraw, double amount);//store=0,withdraw=1;

    internal class ATM
    {
        private String bank;
        private ID id;
        private double storage;
        private double maxAmount=1000000;
        private double BigMoneyBundary = 10000;

        private Random random = new Random();
        public event BigMoneyFetched NoticeBigMoney;

        public String FromBank { get { return bank; } }
        public double Storage {  get { return storage; } }

        public ATM(String bank, ID id, double storage, double max)
        {
            this.bank = bank;
            this.storage = storage;
            this.id = id;
            maxAmount = max;
        }

        public string getID()
        {
            return id.toString();
        }

        /// <summary>
        /// 取钱，返回账户中减少的金额，（非本银行业务将额外收取手续费）
        /// 取款大于ATM存储时抛出异常
        /// </summary>
        /// <param name="account"></param>
        /// <param name="amount"></param>
        /// <param name="info"></param>
        /// <returns></returns>
        /// <exception cref="AccountDealingException"></exception>
        public double withdrawMoney(Account account, double amount, out string info)
        {
            //检测坏钞抛出异常
            int r = random.Next(10);
            if(r<3)
                throw new BadCashException();
            //ATM现金不足抛出异常
            if (amount > storage)
                throw new AccountDealingException(true, true);

            //引发金额过大事件
            if (amount >= BigMoneyBundary)
                NoticeBigMoney.Invoke(true, amount);

            storage-= amount;
            double cost = amount;
            //若不是本银行业务，需要手续费1%
            if (!account.getBank().Equals(bank))
                cost *= 1.01;

            info = "取钱 "+amount+" 元，连手续费共 "+cost+" 元";
            return cost;
        }

        /// <summary>
        /// 存钱，返回账户实际增加的金额，（非本银行业务存在手续费）
        /// 存款超过ATM最大值时抛出异常
        /// </summary>
        /// <param name="account"></param>
        /// <param name="amount"></param>
        /// <param name="info"></param>
        /// <returns></returns>
        public double saveMoney(Account account, double amount, out string info)
        {
            double change = 0;

            //超出ATM最大容量抛出异常
            if(storage+amount > maxAmount)
                throw new AccountDealingException(false, true);

            //金额过大事件
            if (amount >= BigMoneyBundary)
                NoticeBigMoney.Invoke(false, amount);

            storage += amount;
            change = amount;

            //非本银行业务收取手续费
            if (!account.getBank().Equals(bank))
                change *= 0.99;

            info = "存钱 " + amount + " 元，扣除手续费 " + (amount-change) + " 元";
            return change;
        }
    }
}
